import Crypto from '@/libs/crypto-js'
// import axios from '@/js_sdk/gangdiedao-uni-axios'
// import axios from 'axios'
import { Domain, Api, ApiKey } from '@/common/api'
import { json2Form, getWxAppId } from '@/common/util'

const _ = require("@/libs/underscore/underscore-min.js")._

// axios.defaults.withCredentials = true


let Headers = {
  "Content-Type": "application/x-www-form-urlencoded"
}

let waitQueue = []

export const getUrl = (options) => {
    let url = options.url || Domain[Api[options.tag].type] + Api[options.tag].url;
    if (url.indexOf("{{") > -1) {
      let _url = '';
      url = url.split("{{");
      _.each(url, function (v, k) {
        if (v.indexOf("}}") > -1) {
          v = v.split("}}");
          v[0] = options[v[0]] || '';
          v = v[0] + v[1];
        }
        _url += v;
      })
      url = _url;
    }
    return url
}

const md5 = (str) => {
  //var str = Crypto.createHash('md5').update(str).digest('hex');
  return Crypto.MD5(str).toString()
}

const getToken = (o) => {
  var token = '';
  var key = [];
  var value = [];
  _.each(o.data,function(v,k){
    key.push(k);
    value.push(v);
  });
  key.sort();
  //key.reverse();
  _.each(key,function(v,k){token += v+'='+o.data[v]+'&';});
  token = token.substring(0,token.length-1)+o.time+o.apiKey;
  //console.log(token);
  return md5(token)
}

const http = (options) => {
    let params = options.params || {};
    let url = getUrl(options);
    let apiKey = options.apiKey || ApiKey[Api[options.tag].type];
    let timestamp = (new Date().getTime()/1000).toFixed(0);

    //开新内存区存放请求参数
    params = Object.assign({},params);
    params.agent_id = getWxAppId();
    params.token = getToken({data:params, time:timestamp, apiKey:apiKey});
    params.time = timestamp;
    // params = options.method == 'POST' ? json2Form(params) : params;

    let timer = null;
    let requestTask = uni.request({
        url: url,
        header: Headers,
        data: params,
        method: options.method || 'GET',
        dataType: 'json',
        success: (res) => {
			if(res.header["Set-Cookie"]){
				Headers.Cookie = res.header["Set-Cookie"].replace(new RegExp(",", "gm"), ";")
				// console.log(res.header["Set-Cookie"].replace(new RegExp(",", "gm"), ";"))
			}
            clearTimeout(timer);
            if (res.statusCode == 200) {
                if (options.success) options.success(res.data)
            } else {
                if (options.fail) options.fail()
            }
        },
        fail: () => {
            clearTimeout(timer);
            if (options.fail) options.fail()
        }
    });

    timer = setTimeout(() => {
        requestTask.abort(); // 取消请求任务
        if (options.fail) options.fail()
    }, 30000)
 // console.log(options.method)
 
	// let config = options.method == 'POST' ? {
	// 	method: 'post',
	// 	url,
	// 	data: params,
	// 	headers: Headers,
	// 	timeout: options.timeout || 60000 ,//单位ms
	// } : {
	// 	method: options.method || 'post',
	// 	url,
	// 	params,
	// 	headers: Headers,
	// 	timeout: options.timeout || 60000 ,//单位ms
	// };
	
	// axios(config).then(function (response){
	// 	console.log(response)
	// 	if(response.status==200){
	// 		if(options.success)options.success(response.data)
	// 	}else{
	// 		if(options.fail)options.fail(response)
	// 	}
	// 	if(options.complete)options.complete(response)
	// }).catch(function (error){
	// 	if(options.fail)options.fail(error)
	// })
}

export const Request = (options) =>{
    http(options)
}

export const RunWaitQueue =  () => {
    let _t = this;
    _.each(waitQueue, (v) => {
      if (v.status == 'waiting') {
        v.status = 'done';
        http(v.params);
      }
    })
}